import * as echarts from 'echarts';
import {Util} from "@lowcode/jpaas-base-lib";
import ScreenApi from "@/api/screen-api.js";
import ScreenViewManageApi from "@/api/screen/core/screen-view-manage.js";
import busEvent from "@/views/modules/preview/components/js/bus-event.js";
import MapTypes from "@/views/modules/preview/components/common/map-types.js";
import showViewPath from "@/views/modules/preview/components/common/show-view-path.vue";
import { markRaw } from 'vue'
/**
 * 图表公共JS
 * @type {{methods: {}, props: {config: {type: Object}}}}
 */

const ChartPublic = {
    props: {
        chartConfig: {
            type: Object
        },
        screenConfig:{
            type: Object
        },
        drillDownValue:{
            type: String
        },
        //下钻上级
        parentViews:{
            type:Array,
            default:()=>[]
        },
        //路由懒加载文件目录
        loadView:{
            type: Function
        },
    },
    mixins:[busEvent,MapTypes],
    components:{
        showViewPath
    },
    data() {
        return {
            config:this.chartConfig,
            chartPie: null,
            //根据模型查询到的数据
            data: [],
            option:{},
            sql:"",
            //发布事件参数
            params:{},
            //图表过滤参数
            filterParams:[],
            //存放维度数据
            dimensionVals:[],
            //度量的数据
            measureVals:[],
            //存放颜色度量数据
            colorLegendVals:[]
        }
    },
    created() {
        if(!this.config){
            return;
        }
        let mapping = this.config.advancedConf&& this.config.advancedConf.receive?this.config.advancedConf.receive.mapping:[];
        if(mapping && mapping.length>0 ){
            let params={};
            if (this.$route.meta.query) {
                params = JSON.parse(this.$route.meta.query);
            }else {
                params=this.$route.query;
            }
            //筛选器默认参数值
            let filterParams= this.getFilterParams();
            for (let i = 0; i < mapping.length; i++) {
                let value="";
                if(this.config.advancedConf.receive.type=='url'){
                    if(mapping[i].valueSource=='param'){
                        if(params[mapping[i].valueDef]){
                            value=params[mapping[i].valueDef]
                        }else {
                            let arr = mapping[i].name.split(".");
                            let name=arr[arr.length-1];
                            if(params[name]){
                                value=params[name];
                            }
                        }
                    }
                }else  if(filterParams && mapping[i].valueSource=='param'){
                    //计算筛选器默认值
                    if(filterParams[mapping[i].valueDef]){
                        //地图类型参数
                        if(mapping[i].name=="mapType_"){
                            let mapType= this.mapTypes.find(item=>item.label==filterParams[mapping[i].valueDef]);
                            this.config.styles["mapType"]="province";
                            this.config.styles["province"]=mapType?mapType.value:"";
                        }else {
                            value=filterParams[mapping[i].valueDef]
                        }
                    }else {
                        let arr = mapping[i].name.split(".");
                        let name=arr[arr.length-1];
                        if(filterParams[name]){
                            value=filterParams[name];
                        }
                    }
                }
                this.params[mapping[i].name]=value;
            }
        }
        if(this.drillDownValue && this.config.dataSources.filterParams && this.config.dataSources.filterParams.length>0){
            let filterParam=this.config.dataSources.filterParams[0];
            this.filterParams.push({key: filterParam.tableName+"."+filterParam.fieldName, value: this.drillDownValue, opType: "EQ"});
        }
    },
    mounted() {
        let self=this;
        this.getParams(function (res) {
            if(res){
                Object.assign(self.params,res);
            }
            self.initChart();
        })
    },
    methods: {
        /**
         * 初始化图表
         */
        initChart() {
            if(this.chartPie != null && this.chartPie != "" && this.chartPie != undefined) {
                this.chartPie.dispose();
            }
            let pieEl=this.$refs[this.config.key];
            //初始化图表
            //初始化图表
            let language = window.localStorage.getItem('language');
            let locale=language=='en-US'? "EN":"ZH";
            this.chartPie = markRaw(echarts.init(pieEl, 'macarons',{locale :locale}))//获取dom元素
            //静态数据
            if(this.config && this.config.dataSources&& this.config.dataSources.source=="static"){
                this.setOption();
                this.chartPie.resize();
                return;
            }
            //自定义图表不用请求数据
            if(this.config.chartType=='customChart'){
                this.setOption();
                this.chartPie.resize();
                return;
            }
            let measures=[];
            //双y轴
            if(this.config.styles.yAxisShow2 && this.config.dataSources.measures2 && this.config.dataSources.measures2.length>0){
                measures.push(...this.config.dataSources.measures);
                if(this.config.dataSources.measures2){
                    measures.push(...this.config.dataSources.measures2);
                }
            }else {
                measures=this.config.dataSources.measures
            }
            if(!measures || measures.length==0){
                return;
            }
            let obj={
                dataModel:this.config.dataSources.dataModel,
                colorLegends:this.config.dataSources.colorLegends,
                measures:measures,
                dimensions:this.config.dataSources.dimensions,
                params:this.params,
                filterParams:this.filterParams,
                resultNum:this.config.dataSources.resultNum
            }
            let self=this;
            //获取数据
            ScreenViewManageApi.getData(JSON.stringify(obj)).then(res => {
                this.data = res.data;
                this.sql = res.sql;
                //获取初始化数据
                this.getInitData();
                this.setOption();
                //图表点击节点回调事件
                this.chartPie.on('click',function(params){
                    //是否开启联动
                    if(self.config.advancedConf.linkage){
                        let publishParams={
                            component:self.config.key,
                        };
                        if(self.config.advancedConf.publish && self.config.advancedConf.publish.paramMapping.length>0){
                            //未配置颜色图例直接去查data的数据
                            if(self.config.dataSources.colorLegends.length==0){
                                publishParams.params= self.getParamsByData(params);
                            }else {
                                publishParams.params= self.getParamsByConfig(params);
                            }
                        }
                        self.$bus.emit('chartEvent',publishParams);
                    }
                    let drillDownConfig=self.config.advancedConf.drillDownConfig;
                    if(drillDownConfig && drillDownConfig.isDrillDown){
                        self.drillDown(self.config,drillDownConfig,params);
                    }
                });
                this.chartPie.resize();
            });
        },
        //获取初始化数据
        getInitData(){
            //维度
            this.dimensionVals=[];
            for (let i = 0; i < this.config.dataSources.dimensions.length; i++) {
                let dimension = this.config.dataSources.dimensions[i];
                for (let j = 0; j < this.data.length; j++) {
                    let fieldName=dimension.tableName?dimension.tableName+'_'+dimension.fieldName:dimension.fieldName;
                    let dimensionVal =this.data[j][fieldName] || "";
                    let number = this.dimensionVals.indexOf(dimensionVal);
                    if(number==-1) {
                        this.dimensionVals.push(dimensionVal);
                    }
                }
            }
            //度量
            this.measureVals=[];
            for (let i = 0; i < this.config.dataSources.measures.length; i++) {
                let measure = this.config.dataSources.measures[i];
                for (let j = 0; j < this.data.length; j++) {
                    let fieldName=measure.tableName?measure.tableName+'_'+measure.fieldName:measure.fieldName;
                    let measureVal =this.data[j][fieldName];
                    let number = this.measureVals.indexOf(measureVal);
                    if(number==-1) {
                        this.measureVals.push({
                            key:measure.tableName?measure.tableName+'.'+measure.fieldName:measure.fieldName,
                            value:measureVal
                        });
                    }
                }
            }
            //颜色图例
            this.colorLegendVals=[];
            if(this.config.dataSources.colorLegends){
                for (let i = 0; i < this.config.dataSources.colorLegends.length; i++) {
                    let colorLegend = this.config.dataSources.colorLegends[i];
                    for (let j = 0; j < this.data.length; j++) {
                        let fieldName=colorLegend.tableName?colorLegend.tableName+'_'+colorLegend.fieldName:colorLegend.fieldName;
                        let colorValue =this.data[j][fieldName];
                        let number = this.colorLegendVals.indexOf(colorValue);
                        if(number==-1) {
                            this.colorLegendVals.push(colorValue);
                        }
                    }
                }
            }
        },
        //获取维度
        getDimensions(xAxisArr){
            let xAxisData=[];
            for (let i = 0; i < this.data.length; i++) {
                let xAxisValue="";
                let oldValue="";
                let key="";
                //维度
                for (let j = 0; j < this.config.dataSources.dimensions.length; j++) {
                    let dimension = this.config.dataSources.dimensions[j];
                    let fieldName=dimension.tableName?dimension.tableName+'_'+dimension.fieldName:dimension.fieldName;
                    if(xAxisValue==""){
                        xAxisValue=this.data[i][fieldName] || "";
                        if(typeof(xAxisValue)!='string'){
                            oldValue=xAxisValue.oldValue || "";
                            xAxisValue=xAxisValue.newValue || "";
                        }
                        key=fieldName;
                    }else {
                        let val=this.data[i][fieldName] || "";
                        if(typeof(val)!='string'){
                            oldValue=xAxisValue+"-"+val.oldValue || "";
                            xAxisValue+=xAxisValue+"-"+val.newValue || "";
                        }else {
                            oldValue+="-"+val;
                            xAxisValue+="-"+val;
                        }
                        key+="-"+fieldName;
                    }
                }
                let number = xAxisData.indexOf(xAxisValue);
                if(number==-1){
                    xAxisData.push(xAxisValue);
                }
                if(xAxisArr){
                    if(oldValue){
                        let item = xAxisArr.find((info) => info.value == oldValue )
                        if(!item){
                            xAxisArr.push({
                                key:key,
                                value:oldValue
                            });
                        }
                    }else {
                        let item = xAxisArr.find((info) => info.value == xAxisValue )
                        if(!item){
                            xAxisArr.push({
                                key:key,
                                value:xAxisValue
                            });
                        }
                    }

                }
            }
            let xAxis={
                data: xAxisData,
                show:this.config.styles.xAxisShow,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color:this.config.advancedConf.xAxisColor?this.config.advancedConf.xAxisColor:"#333"
                    }
                },
            }
            return xAxis;
        },
        //根据data取参数
        getParamsByData(clickObj){
            let params= {};
            let paramMapping=this.config.advancedConf.publish.paramMapping;
            //地图 点击对象无数据则给null
            if(this.config.chartType==="map" && !clickObj.data ){
                for (let i = 0; i < paramMapping.length; i++) {
                    if(paramMapping[i].key=="mapType_"){
                        params[paramMapping[i].key]=clickObj.name;
                    } else if(!params[paramMapping[i].key]){
                        params[paramMapping[i].key]="null";
                    }
                }
                return params;
            }
            for (let i = 0; i <paramMapping.length ; i++) {
                let value="";
                if(paramMapping[i].key=="mapType_"){
                    value=clickObj.name;
                }else {
                    let key = (paramMapping[i].key).replace(".","_");
                    value = this.data[clickObj.dataIndex][key];
                }
                if(!value){
                    continue;
                }
                //配置了字段渲染
                if(typeof(value) !="string"){
                    params[paramMapping[i].key]=value.oldValue;
                }else {
                    params[paramMapping[i].key]=value;
                }
            }
            return params;
        },
        //根据配置取参数 clickObj:点击的对象
        getParamsByConfig(clickObj){
            let params= {};
            let paramMapping=this.config.advancedConf.publish.paramMapping;
            //地图 点击对象无数据则给null
            if(this.config.chartType==="map" && !clickObj.data ){
                for (let i = 0; i < paramMapping.length; i++) {
                    if(paramMapping[i].key=="mapType_"){
                        params[paramMapping[i].key]=clickObj.name;
                    } else if(!params[paramMapping[i].key]){
                        params[paramMapping[i].key]="null";
                    }
                }
                return params;
            }
            for (let i = 0; i <paramMapping.length ; i++) {
                let value="";
                //地图类型
                if(paramMapping[i].key=="mapType_"){
                    value=clickObj.name;
                    params[paramMapping[i].key]=value;
                    continue;
                }
                //维度
                for (let j = 0; j < this.config.dataSources.dimensions.length; j++) {
                    let dimension = this.config.dataSources.dimensions[j];
                    let key=dimension.tableName+"."+dimension.fieldName;
                    if(paramMapping[i].key==key){
                        let dimensionVal = this.dimensionVals[clickObj.dataIndex];
                        if(dimensionVal){
                            //配置了字段渲染
                            if(typeof(dimensionVal) !="string" ){
                                value=dimensionVal.oldValue;
                            }else {
                                value=dimensionVal;
                            }
                            break;
                        }
                    }
                }
                if(value!=""){
                    params[paramMapping[i].key]=value;
                    continue;
                }
                //度量
                for (let j = 0; j < this.config.dataSources.measures.length; j++) {
                    let measure = this.config.dataSources.measures[j];
                    let key=measure.tableName+"."+measure.fieldName;
                    if(paramMapping[i].key==key){
                        let index=(clickObj.dataIndex+1) * (clickObj.componentIndex+1);
                        if(this.measureVals[index] && this.measureVals[index-1].key==paramMapping[i].key){
                            value= this.measureVals[index].value;
                        }
                    }
                }
                if(value!=""){
                    params[paramMapping[i].key]=value;
                    continue;
                }
                //颜色图例
                for (let j = 0; j < this.config.dataSources.colorLegends.length; j++) {
                    let colorLegend = this.config.dataSources.colorLegends[j];
                    let key=colorLegend.tableName+"."+colorLegend.fieldName;
                    if(paramMapping[i].key==key){
                        let index=(clickObj.componentIndex)%this.colorLegendVals.length;
                        value=this.colorLegendVals[index];
                    }
                }
                if(value!=""){
                    params[paramMapping[i].key]=value;
                    continue;
                }

            }
            return params;
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys
        },
        /**
         *
         */
        addParams() {
            if (this.config.advancedConf.receive.mapping.length >= this.listParamsDef.length) {
                this.$notification.warning({
                    message: '提示信息',
                    description: '该组件未配置传入参数，请去配置!',
                })
                return
            }
            this.config.advancedConf.receive.mapping.push({ idx_: Util.randomId(), name: '', valueSource: '', valueDef: '' })
        },
        moveUp() {
            this.toUp(this.config.advancedConf.receive.mapping, this.selectedRowKeys)
        },
        moveDown() {
            this.toDown(this.config.advancedConf.receive.mapping, this.selectedRowKeys)
        },
        removeSelect() {
            this.removeRows(this.config.advancedConf.receive.mapping, this.selectedRowKeys)
        },
        //处理接收到的事件
        handReceive(args) {
            let receive = this.config.advancedConf.receive;
            if ( (receive.type=='event' &&receive.publishComponent == args.component)) {
                let inputParams = args.params;
                let params = {};
                //读取配置的参数
                for (let i = 0; i < receive.mapping.length; i++) {
                    let o = receive.mapping[i];
                    if (o.valueSource == 'param' && inputParams[o.valueDef]) {
                        //地图类型参数
                        if(o.valueDef=="mapType_" || o.name=="mapType_"){
                            let mapType= this.mapTypes.find(item=>item.label==inputParams[o.valueDef]);
                            this.config.styles["mapType"]="province";
                            this.config.styles["province"]=mapType?mapType.value:"";
                        }else {
                            params[o.name] = inputParams[o.valueDef];
                        }
                    }
                }
                this.params=params;
                //初始化图表
                this.initChart();
            }
        },
        //图表过滤条件查询
        paramsChange(params){
            this.filterParams=[];
            for (let i = 0; i <params.length ; i++) {
                let value = params[i].value;
                if(value){
                    this.filterParams.push({
                        key:params[i].tableName+"."+params[i].fieldName,
                        value:value,
                        controlType:params[i].condition.controlType,
                        opType:params[i].condition.opType
                    })
                }
            }
            //初始化图表
            this.initChart();
        },
        //获取颜色维度值
        getColorValue(data,colorLegend,measure,isJoin){
            let fieldName=colorLegend.tableName?colorLegend.tableName+'_'+colorLegend.fieldName:colorLegend.fieldName
            let colorValue="";
            if(isJoin && this.config.styles.joinMeasure){
                colorValue=data[fieldName]+"-"+measure.fieldLabel;
            }else {
                colorValue =data[fieldName];
            }
            return colorValue;
        },
        getColors(){
            //颜色配置 先取全局配置
            let colors=this.screenConfig?this.screenConfig.globalConfig.colors:[];
            if(this.config.styles.colors && this.config.styles.colors.length>0 ){
                colors=this.config.styles.colors;
            }
            return colors;
        },
        getParams(callback){
            if(!this.config){
                return;
            }
            if(!this.config.advancedConf.receive || !this.config.advancedConf.receive.mapping){
                callback({});
                return;
            }
            ScreenApi.getParams(JSON.stringify(this.config.advancedConf.receive.mapping)).then(res=>{
                callback(res);
            }).catch(err=>{
                callback({});
            })
        },
        //随着屏幕大小调节图表
        mouseup(){
            if(this.chartPie && this.chartPie.resize()){
                this.chartPie.resize();
            }
        },
    },
    watch:{
        option:{
            handler: function (val, oldVal) {
                let self=this;
                self.chartPie.setOption(val);
            },
            deep: true
        },
        config:{
            handler: function (val, oldVal) {
                let self=this;
                setTimeout(function () {
                    self.$emit("setChartComponent",val);
                    self.initChart();
                },1000)
            },
            deep: true
        },
        "screenConfig.globalConfig":{
            handler: function (val, oldVal) {
                let self=this;
                setTimeout(function () {
                    self.initChart();
                },1000)
            },
            deep: true
        }
    }

}

export default ChartPublic;
